package org.jeecg.modules.demo.mes.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.mes.entity.MesTechnology;
import org.jeecg.modules.demo.mes.service.IMesTechnologyService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 工艺表
 * @Author: jeecg-boot
 * @Date: 2022-10-31
 * @Version: V1.0
 */
@Api(tags = "工艺表")
@RestController
@RequestMapping("/mes/mesTechnology")
@Slf4j
public class MesTechnologyController extends JeecgController<MesTechnology, IMesTechnologyService> {
    @Autowired
    private IMesTechnologyService mesTechnologyService;

    /**
     * 分页列表查询
     *
     * @param mesTechnology
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "工艺表-分页列表查询")
    @ApiOperation(value = "工艺表-分页列表查询", notes = "工艺表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<MesTechnology>> queryPageList(MesTechnology mesTechnology,
                                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                      HttpServletRequest req) {
        QueryWrapper<MesTechnology> queryWrapper = QueryGenerator.initQueryWrapper(mesTechnology, req.getParameterMap());
        Page<MesTechnology> page = new Page<MesTechnology>(pageNo, pageSize);
        IPage<MesTechnology> pageList = mesTechnologyService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param mesTechnology
     * @return
     */
    @AutoLog(value = "工艺表-添加")
    @ApiOperation(value = "工艺表-添加", notes = "工艺表-添加")
    //@RequiresPermissions("org.jeecg.modules.demo:mes_technology:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody MesTechnology mesTechnology) {
        //校验工艺名
        checkTechnologyName(mesTechnology);
        mesTechnologyService.save(mesTechnology);
        return Result.OK("添加成功！");
    }

    /**
     * 校验工艺名的唯一性
     */
    private void checkTechnologyName(MesTechnology mesTechnology) {
        final String technologyName = mesTechnology.getTechnologyName();
        if (StringUtils.isBlank(technologyName)) {
            throw new JeecgBootException("工艺名称不能为空");
        }
        final Map<String, Object> cxMap = new HashMap<>();
        cxMap.put("technologyName", technologyName);
        final List<MesTechnology> list = mesTechnologyService.queryTechnologyListSelective(cxMap);
        if (list == null || list.size() == 0) {
            return;
        }
        final String id = mesTechnology.getId();
        final String exMsg = "工艺名称不能重复";
        if (StringUtils.isBlank(id)) {
            throw new JeecgBootException(exMsg);
        }
        //编辑
        if (list.size() > 1) {
            throw new JeecgBootException(exMsg);
        }
        final MesTechnology mesTechnologyFromDB = list.get(0);
        if (!StringUtils.equals(id,mesTechnologyFromDB.getId())){
            throw new JeecgBootException(exMsg);
        }

    }

    /**
     * 编辑
     *
     * @param mesTechnology
     * @return
     */
    @AutoLog(value = "工艺表-编辑")
    @ApiOperation(value = "工艺表-编辑", notes = "工艺表-编辑")
    //@RequiresPermissions("org.jeecg.modules.demo:mes_technology:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody MesTechnology mesTechnology) {
        checkTechnologyName(mesTechnology);
        mesTechnologyService.updateById(mesTechnology);
        return Result.OK("编辑成功!");
    }

    /**
     * 工艺禁用|启用
     */
    @AutoLog(value = "工艺表-修改状态")
    @ApiOperation(value = "工艺表-修改状态", notes = "工艺表-修改状态")
    @RequestMapping(value = "/changeStatus", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> changeStatus(@RequestBody MesTechnology mesTechnology,HttpServletRequest request) {
        final String id = mesTechnology.getId();
        if (StringUtils.isBlank(id)){
            throw new JeecgBootException("唯一id为空");
        }
        final String technologyStatus = mesTechnology.getTechnologyStatus();
        if (StringUtils.isBlank(technologyStatus) || !Arrays.asList("1","2").contains(technologyStatus)){
            throw new JeecgBootException("非法的工艺状态");
        }
        //工艺一条生产线只能有一个启用
        checkTechnologyFactoryLine(mesTechnology);
        mesTechnologyService.updateStatusById(id,technologyStatus, JwtUtil.getUserNameByToken(request));
        return Result.OK("操作成功!");
    }

    /**
     * 工艺一条生产线只能有一个启用
     */
    private void checkTechnologyFactoryLine(MesTechnology mesTechnology) {
        final String technologyStatus = mesTechnology.getTechnologyStatus();
        if (!StringUtils.equals("1",technologyStatus)){
            return;
        }
        final String id = mesTechnology.getId();
        final MesTechnology byId = mesTechnologyService.getById(id);
        //查询统一生产线上是否存在另外一条已经启动的工艺
        final Map<String,Object> cxMap =  new HashMap<>();
        cxMap.put("factoryId",byId.getFactoryId());
        cxMap.put("workshopId",byId.getWorkshopId());
        cxMap.put("lineId",byId.getLineId());
        cxMap.put("technologyStatus","1");
        final List<MesTechnology> mesTechnologyList = mesTechnologyService.queryTechnologyListSelective(cxMap);
        if (mesTechnologyList!=null && mesTechnologyList.size()>0){
            throw new JeecgBootException("该生产线已经有一个工艺处于启用状态，只能有一个工艺处于启用状态");
        }
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "工艺表-通过id删除")
    @ApiOperation(value = "工艺表-通过id删除", notes = "工艺表-通过id删除")
    //@RequiresPermissions("org.jeecg.modules.demo:mes_technology:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        mesTechnologyService.removeTechnologyById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "工艺表-批量删除")
    @ApiOperation(value = "工艺表-批量删除", notes = "工艺表-批量删除")
    //@RequiresPermissions("org.jeecg.modules.demo:mes_technology:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.mesTechnologyService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "工艺表-通过id查询")
    @ApiOperation(value = "工艺表-通过id查询", notes = "工艺表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<MesTechnology> queryById(@RequestParam(name = "id", required = true) String id) {
        MesTechnology mesTechnology = mesTechnologyService.getById(id);
        if (mesTechnology == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(mesTechnology);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param mesTechnology
     */
    //@RequiresPermissions("org.jeecg.modules.demo:mes_technology:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MesTechnology mesTechnology) {
        return super.exportXls(request, mesTechnology, MesTechnology.class, "工艺表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("mes_technology:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MesTechnology.class);
    }

}
